package com.login.client.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.rmi.ServerException;
import java.time.Duration;
import java.util.Map;

/**
 * HTTP客户端工具类
 *
 * @author jcl
 * @date 2025/3/14 15:20
 */
@Slf4j
public class HttpClientUtil {

    private static final HttpClient httpClient;

    static {
        // 配置HttpClient的全局设置
        httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10)) // 设置连接超时时间为3秒
                .build();
    }

    /**
     * 发送GET请求
     *
     * @param url 请求的URL
     * @return 响应体
     */
    public static String sendGetRequest(String url) {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(3)) // 设置请求超时时间为3秒
                .GET()
                .build();

        HttpResponse<String> response = null;
        try {
            response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            log.error("http请求异常", e);
            return "";
        }

        return response.body();
    }

    /**
     * 发送GET请求
     *
     * @param url    请求的基础URL（不带参数）
     * @param params 请求参数的Map，可以为null
     * @return 响应体
     */
    public static String sendGetRequest(String url, Map<String, Object> params) {
        // 构建带参数的URL
        String fullUrl = buildUrlWithParams(url, params);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fullUrl))
                .timeout(Duration.ofSeconds(5)) // 设置请求超时时间为3秒
                .GET()
                .build();

        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        } catch (IOException | InterruptedException e) {
            log.error("http请求异常", e);
            return "";

        }
    }

    /**
     * 发送GET请求，支持实体对象参数和请求头
     *
     * @param url     请求的URL
     * @param params  请求参数实体对象
     * @param headers 请求头Map
     * @return 响应体
     */
    public static String sendGetRequestWithEntityAndHeaders(String url, Map<String, Object> params, Map<String, String> headers) {
        // 构建带参数的URL
        String fullUrl = buildUrlWithParams(url, params);
        System.out.println("Calling URL: " + fullUrl); // 调试

        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(fullUrl))
                .timeout(Duration.ofSeconds(15)) // 延长超时
                .GET();

        // 添加请求头
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.header(entry.getKey(), entry.getValue());
            }
        }

        HttpRequest request = requestBuilder.build();

        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        } catch (IOException | InterruptedException e) {
            log.error("http请求异常", e);
            return "";
        }
    }

    /**
     * 构建带参数的URL
     *
     * @param baseUrl 基础URL
     * @param params  参数Map
     * @return 完整的URL
     */
    private static String buildUrlWithParams(String baseUrl, Map<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }

        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (queryString.length() > 0) {
                queryString.append("&");
            }
            queryString.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8))
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
        }

        // 处理URL中可能已经包含?的情况
        String separator = baseUrl.contains("?") ? "&" : "?";
        return baseUrl + separator + queryString;
    }

    /**
     * 发送POST请求
     *
     * @param url         请求的URL
     * @param requestBody 请求体
     * @return 响应体
     */
    public static String sendPostRequest(String url, String requestBody) {
        HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(requestBody);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .timeout(Duration.ofSeconds(3)) // 设置请求超时时间为3秒
                .POST(bodyPublisher)
                .build();

        HttpResponse<String> response = null;
        try {
            response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            log.error("http请求异常", e);
            return "";
        }
        return response.body();
    }

    public static String sendFormPostRequest(String url, String formData) {
        HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(formData);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/x-www-form-urlencoded") // 关键修改
                .timeout(Duration.ofSeconds(3))
                .POST(bodyPublisher)
                .build();
        HttpResponse<String> response = null;
        try {
            response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            log.error("http请求异常", e);
            return "";
        }
        return response.body();
    }

    /**
     * 发送POST请求，带有请求头
     *
     * @param url         请求的URL
     * @param headers     请求头
     * @param requestBody 请求体
     * @return 响应体
     * @throws IOException          如果发生I/O错误
     * @throws InterruptedException 如果请求被中断
     */
    public static String sendPostRequestWithHeaders(String url, Map<String, String> headers, String requestBody) {
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(10)) // 设置请求超时时间为3秒
                .POST(HttpRequest.BodyPublishers.ofString(requestBody));

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            requestBuilder.header(entry.getKey(), entry.getValue());
        }

        HttpRequest request = requestBuilder.build();

        HttpResponse<String> response = null;
        try {
            response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            log.error("http请求异常", e);
            return "";
        }
        return response.body();
    }
}
